// 获取应用实例
const app = getApp();

// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");
const message = db.collection("message");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    avatarUrl: {
      type: String,
      value: "",
    },
    nickname: {
      type: String,
      value: "",
    },
    openid: {
      type: String,
      value: "",
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    disabled: false,
    fileID: '',
    o_openid: wx.getStorageSync('o_openid')
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      // console.log(avatarUrl);
      this.uploadImage(avatarUrl);
    },

    getUserName(e) {
      const that = this;
      let { nickname, avatarUrl, openid } = that.properties;
      let { o_openid, fileID } = that.data;
      nickname = e.detail.value.nickname;
      that.setData({
        nickname,
      });
      if (
        avatarUrl ==
        "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
      ) {
        wx.showToast({
          title: "请填入图像",
          icon: "none",
        });
      } else if (nickname == "微信用户") {
        wx.showToast({
          title: "请输入昵称",
          icon: "none",
        });
      } else {
        uimg.where({ _openid: openid }).get({
          success: res => {
            const data = res.data[0];
            if (o_openid) {
              let { love_word } = res.data[0];
              love_word.forEach(i => {
                if (i.openid == openid) {
                  i.avatarUrl = avatarUrl;
                  i.nickname = nickname;
                }
              });
              uimg.where({ _openid: openid }).update({
                data: {
                  love_word
                },
                success: res => {
                  uimg.where({ _openid: o_openid }).update({
                    data: {
                      love_word
                    },
                  })
                }
              });
            }
            if (data.fileID != '' && fileID != '') {
              that.delOldAvatar(data.fileID);
            }
          }
        })

        // 判断昵称
        if (nickname == '') {
          wx.showToast({
            title: '昵称不能为空',
            icon: 'none'
          })
          return;
        }

        if (that.data.fileID != '') {

          uimg.where({ _openid: openid }).update({
            data: {
              avatarUrl,
              nickname,
              fileID: that.data.fileID
            },
            success: (res) => {
              that.triggerEvent("setUser", {
                hasUserInfo: true,
                avatarUrl,
                nickname,
              });
            },
          });
          message.where({ _openid: openid }).update({
            data: {
              avatarUrl,
              nickname,
            },
          });
        } else {
          uimg.where({ _openid: openid }).update({
            data: {
              nickname,
            },
            success: (res) => {
              that.triggerEvent("setUser", {
                hasUserInfo: true,
                avatarUrl,
                nickname,
              });
            },
          });
          message.where({ _openid: openid }).update({
            data: {
              nickname,
            },
          });
        }

        that.setData({
          fileID: ''
        })
      }
    },

    // 上传到云储存
    uploadImage(fileURL) {
      var that = this;
      that.setData({
        disabled: true,
      });
      wx.cloud.uploadFile({
        cloudPath: "uimg/uimg" + new Date().getTime() + ".png", // 上传至云端的路径
        filePath: fileURL, // 小程序临时文件路径
        success: (res) => {
          if (that.data.fileID != '') {
            that.delOldAvatar(that.data.fileID);
          }
          //获取图片的http路径，准备添加到数据库中
          // console.log(res.fileID);
          that.addImagePath(res.fileID);
          that.setData({
            fileID: res.fileID,
          });
        },
        fail: () => {
          wx.showToast({
            title: "获取失败",
            icon: "error",
          });
        },
      });
    },

    // 获取图片上传后的url路径
    addImagePath(fileId) {
      // console.log(fileId);
      var that = this;
      wx.cloud.getTempFileURL({
        fileList: [fileId],
        success: (res) => {
          const url = res.fileList[0].tempFileURL;
          // console.log(url);
          that.setData({
            avatarUrl: url,
            disabled: false,
          });
        },
        fail: () => {
          wx.showToast({
            title: "获取失败",
            icon: "error",
          });
        },
      });
    },

    closeUserInfoMask() {
      this.triggerEvent("closeUserInfoMask");
      if (this.data.fileID != '') {
        this.delOldAvatar(this.data.fileID);
        this.setData({ fileID: '' });
      }
    },

    delOldAvatar(fileID) {
      wx.cloud.deleteFile({
        fileList: [fileID],
        success(res) {
          console.log(res, '删除文件')
        },
        fail(err) {
          console.log(err)
        }
      });
    }
  },
});
